/**
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.aiwei.tdjk.controller;


import com.aiwei.tdjk.bean.Menu;
import com.aiwei.tdjk.entity.LoginLog;
import com.aiwei.tdjk.entity.User;
import com.aiwei.tdjk.service.LoginLogService;
import com.aiwei.tdjk.service.ResourceService;
import com.aiwei.tdjk.service.UserService;
import com.aiwei.tdjk.utils.UserUtil;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

/**
 * <p>User: yanfeng
 * <p>Date: 16-12-13 下午10:15
 * <p>Version: 1.0
 */
@Controller("adminIndexController")
@RequestMapping("/admin")
public class IndexController {

    @Autowired
    private ResourceService resourceService;
    @Autowired
    private UserService userService;

    @Autowired
    private LoginLogService loginLogService;

    static Logger logger = Logger.getLogger(IndexController.class);



    @RequestMapping(value = "/main")
    public String main(Model model) {
        List<Menu> menus = resourceService.findMenus(UserUtil.getUserFromSession());
        model.addAttribute("menus", menus);
        model.addAttribute("user",userService.get(UserUtil.getUserFromSession().getId()));
        return "admin/index/main";
    }

    @RequestMapping(value = "/logout")
    public String logout() {

        User user = UserUtil.getUserFromSession();
        if(user==null){
            return "redirect:/login.jsp";
        }
        LoginLog loginLog = new LoginLog();
        loginLog.setUserId(user.getId());
        loginLog.setLoginIp(SecurityUtils.getSubject().getSession().getHost());
        loginLog.setUsername(user.getUsername());
        loginLog.setOperate("登出");
        loginLogService.add(loginLog);
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            subject.logout(); // session 会销毁，在SessionListener监听session销毁，清理权限缓存
//                logger.info("用户" + UserUtil.getUserFromSession().getUsername() + "退出登录");
        }
        return "redirect:/login.jsp";
    }

}
